package com.example.chasshelper.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.chasshelper.db.AppSQLiteHelper;
import com.example.chasshelper.model.Classroom;
import com.example.chasshelper.model.Course;
import com.example.chasshelper.model.Message;
import com.example.chasshelper.model.Student;
import com.example.chasshelper.model.Teacher;
import com.example.chasshelper.model.Test;
import com.example.chasshelper.utils.OkHttpUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ClassroomDao {
    private OkHttpClient okHttpClient = OkHttpUtils.getClient();
    private String ipUrl = OkHttpUtils.getUrl();
    private String url;

    /*
     * 查询所有
     * */
    public List<Classroom> findAll() {
        url = ipUrl + "/classroom/findAll";
        System.out.println("url:" + url);
        List<Classroom> list = new ArrayList<>();
        Request request = new Request.Builder().url(url).get().build();
        try {
            //执行同步get请求
            Response response = okHttpClient.newCall(request).execute();
            //获得返回的字符串
            String string = response.body().string();
            //开始解析服务器传过来的json数据
            Gson gson = new Gson();
            //传过来的是list，需要用泛型来接收
            Type type = new TypeToken<List<Classroom>>() {
            }.getType();
            list = gson.fromJson(string, type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /*
     * 根据教师id查询课堂
     * */
    public List<Classroom> findByTeacherId(Teacher teacher) {
        url = ipUrl + "/classroom/findByTeacherId?teacherId="+teacher.getTeacherId();
        System.out.println("url:"+url);
        List<Classroom> list = new ArrayList<>();
        Request request = new Request.Builder().url(url).get().build();
        try {
            //执行同步get请求
            Response response = okHttpClient.newCall(request).execute();
            //获得返回的字符串
            String string =response.body().string();
            //开始解析服务器传过来的json数据
            Gson gson = new Gson();
            //传过来的是list，需要用泛型来接收
            Type type = new TypeToken<List<Classroom>>() {}.getType();
            list = gson.fromJson(string, type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /*
     * 根据学生id查询课堂
     * */
    public List<Classroom> findByStudentId(Student student) {
        url = ipUrl + "/classroom/findByStudentId?studentId="+student.getStudentId();
        System.out.println("url:" + url);
        List<Classroom> list = new ArrayList<>();
        Request request = new Request.Builder().url(url).get().build();
        try {
            //执行同步get请求
            Response response = okHttpClient.newCall(request).execute();
            //获得返回的字符串
            String string = response.body().string();
            //开始解析服务器传过来的json数据
            Gson gson = new Gson();
            //传过来的是list，需要用泛型来接收
            Type type = new TypeToken<List<Classroom>>() {
            }.getType();
            list = gson.fromJson(string, type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /*
     * 根据教师id以及课程名或id模糊查询
     * */
    public List<Classroom> findByClassroomNameContainingAndTeacher_TeacherId(String factor,Teacher teacher) {
        System.out.println(factor);
        if (factor==null||factor.equals("")) {
            url = ipUrl + "/classroom/findByIdOrCourseNameLike?teacherId="+teacher.getTeacherId();
        } else {
            url = ipUrl + "/classroom/findByIdOrCourseNameLike?factor=" + factor+"&teacherId="+teacher.getTeacherId();
        }

        System.out.println("url:"+url);
        List<Classroom> list = new ArrayList<>();
        Request request = new Request.Builder().url(url).get().build();
        try {
            //执行同步get请求
            Response response = okHttpClient.newCall(request).execute();
            //获得返回的字符串
            String string =response.body().string();
            //开始解析服务器传过来的json数据
            Gson gson = new Gson();
            //传过来的是list，需要用泛型来接收
            Type type = new TypeToken<List<Classroom>>() {}.getType();
            list = gson.fromJson(string, type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /*
     * 根据id查询教师用户
     * */
    public Teacher findTeacher(Classroom classroom) {
        url = ipUrl + "/classroom/findTeacher?classroomId="+classroom.getClassroomId();
        System.out.println("url:"+url);
        Teacher teacher=null;
        Request request = new Request.Builder().url(url).get().build();
        try {
            //执行同步get请求
            Response response = okHttpClient.newCall(request).execute();
            //获得返回的字符串
            String string =response.body().string();
            //开始解析服务器传过来的json数据
            Gson gson = new Gson();
            //接收数据
            teacher = gson.fromJson(string, Teacher.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(teacher);
        return teacher;
    }

    /*
     * 设置开始上课
     * */
    public void startClassroom(Classroom classroom) {

        url = ipUrl + "/classroom/update?classroomId=" + classroom.getClassroomId() + "&classroomState=进行中";
        System.out.println("url:" + url);
        Request request = new Request.Builder().url(url).get().build();
        final Map<String, Object> resultMap = new HashMap<>();
        //执行异步get请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("成功");
            }
        });
    }

    /*
     * 设置已下课
     * */
    public void endClassroom(Classroom classroom) {
        url = ipUrl + "/classroom/update?classroomId=" + classroom.getClassroomId() + "&classroomState=已结束";
        System.out.println("url:" + url);
        Request request = new Request.Builder().url(url).get().build();
        final Map<String, Object> resultMap = new HashMap<>();
        //执行异步get请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("成功");
            }
        });
    }

    /*
     * 设置开始签到
     * */
    public void startSignIn(Classroom classroom) {
        url = ipUrl + "/classroom/update?classroomId=" + classroom.getClassroomId() + "&classroomSignFlag=进行中";
        System.out.println("url:" + url);
        Request request = new Request.Builder().url(url).get().build();
        final Map<String, Object> resultMap = new HashMap<>();
        //执行异步get请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("成功");
            }
        });
    }

    /*
     * 设置签到已结束
     * */
    public void endSignIn(Classroom classroom) {
        url = ipUrl + "/classroom/update?classroomId=" + classroom.getClassroomId() + "&classroomSignFlag=已结束";
        System.out.println("url:" + url);
        Request request = new Request.Builder().url(url).get().build();
        final Map<String, Object> resultMap = new HashMap<>();
        //执行异步get请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("成功");
            }
        });
    }

    /*
     * 根据id查询
     * */
    public Classroom findById(Integer id) {
        url = ipUrl + "/classroom/findById?classroomId=" + id;
        System.out.println("url:" + url);
        Classroom classroom = new Classroom();
        Request request = new Request.Builder().url(url).get().build();
        try {
            //执行同步get请求
            Response response = okHttpClient.newCall(request).execute();
            //获得返回的字符串
            String string = response.body().string();
            //开始解析服务器传过来的json数据
            Gson gson = new Gson();
            //接收数据
            classroom = gson.fromJson(string, Classroom.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return classroom;
    }

    /*
     * 根据id查询题目
     * */
    public List<Test> findTest(Classroom classroom) {
        url = ipUrl + "/classroom/findTest?classroomId=" + classroom.getClassroomId();
        System.out.println("url:" + url);
        List<Test> list = new ArrayList<>();
        Request request = new Request.Builder().url(url).get().build();
        try {
            //执行同步get请求
            Response response = okHttpClient.newCall(request).execute();
            //获得返回的字符串
            String string = response.body().string();
            //开始解析服务器传过来的json数据
            Gson gson = new Gson();
            //传过来的是list，需要用泛型来接收
            Type type = new TypeToken<List<Test>>() {
            }.getType();
            list = gson.fromJson(string, type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /*
     * 设置开始测验
     * */
    public void startTest(Classroom classroom) {
        url = ipUrl + "/classroom/update?classroomId=" + classroom.getClassroomId() + "&classroomTestFlag=进行中";
        System.out.println("url:" + url);
        Request request = new Request.Builder().url(url).get().build();
        final Map<String, Object> resultMap = new HashMap<>();
        //执行异步get请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("成功");
            }
        });
    }

    /*
     * 设置测验已结束
     * */
    public void endTest(Classroom classroom) {
        url = ipUrl + "/classroom/update?classroomId=" + classroom.getClassroomId() + "&classroomTestFlag=已结束";
        System.out.println("url:" + url);
        Request request = new Request.Builder().url(url).get().build();
        final Map<String, Object> resultMap = new HashMap<>();
        //执行异步get请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("成功");
            }
        });
    }

    /*
     * 添加测验题目
     * */
    public void addTest(Classroom classroom,Test test) {

        url = ipUrl + "/classroom/addTest?classroomId=" + classroom.getClassroomId() + "&testId="+test.getTestId();
        System.out.println("url:" + url);
        Request request = new Request.Builder().url(url).get().build();
        final Map<String, Object> resultMap = new HashMap<>();
        //执行异步get请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("成功");
            }
        });
    }


/*************************************************************************************************************************************************/

/*
    private String tableName="classroom";
    private AppSQLiteHelper appSQLiteHelper;

    public ClassroomDao(Context context) {
        appSQLiteHelper = new AppSQLiteHelper(context);

    }

    */
    /*
     * 添加
     * *//*

    public boolean insert(Classroom classroom) {
        SQLiteDatabase sqLiteDatabase = appSQLiteHelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name",classroom.getName());
        contentValues.put("create_time",classroom.getCreate_time());
        contentValues.put("c_id",classroom.getC_id());
        long insert = sqLiteDatabase.insert(tableName, null, contentValues);
        System.out.println("ClassroomDao.insert()):"+insert);
        sqLiteDatabase.close();
        return insert > 0;
    }
    */
    /*
     * 删除
     * *//*

    public boolean delete(Integer cr_id) {
        SQLiteDatabase sqLiteDatabase = appSQLiteHelper.getWritableDatabase();
        long delete = sqLiteDatabase.delete(tableName, "cr_id=", new String[]{cr_id + ""});
        System.out.println("ClassroomDao.delete()):"+delete);
        sqLiteDatabase.close();
        return delete > 0;
    }
    */
    /*
     * 修改
     * 唯一标识必须命名为id
     * *//*

    public boolean update(Classroom classroom, Integer cr_id) {
        SQLiteDatabase sqLiteDatabase = appSQLiteHelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name",classroom.getName());
        contentValues.put("create_time",classroom.getCreate_time());
        contentValues.put("c_id",classroom.getC_id());
        long update = sqLiteDatabase.update(tableName, contentValues, "cr_id=?", new String[]{String.valueOf(cr_id)});
        System.out.println("ClassroomDao.update()):"+update);
        sqLiteDatabase.close();
        return update > 0;
    }
    */
    /*
     * 无条件查询
     * *//*

    public List<Classroom> queryAll() {
        SQLiteDatabase sqLiteDatabase = appSQLiteHelper.getReadableDatabase();
        List<Classroom>list = null;
        Classroom classroom;
        Cursor cursor = sqLiteDatabase.query(tableName, null, null, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            list = new ArrayList<>();
            while (cursor.moveToNext()) {
                classroom = new Classroom();
                classroom.setCr_id(Integer.valueOf(cursor.getString(cursor.getColumnIndex("cr_id"))));
                classroom.setName(cursor.getString(cursor.getColumnIndex("name")));
                classroom.setCreate_time(cursor.getString(cursor.getColumnIndex("create_time")));
                classroom.setC_id(Integer.valueOf(cursor.getString(cursor.getColumnIndex("c_id"))));
                list.add(classroom);
            }
        }
        System.out.println("ClassroomDao.queryAll())!");
        sqLiteDatabase.close();
        return list;
    }

*/
}
